package zack.gateway.core.authorization;

import com.alibaba.fastjson2.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author A1793
 */
public class JwtUtil {

    private static final String signingKey = "B*B^5Fe";

    public static String encode(String issuer,long ttlMills,Map<String,Object> claims){
        if(claims == null){
            claims = new HashMap<String,Object>();
        }
        long currentTimeMillis = System.currentTimeMillis();
        Date date = new Date(currentTimeMillis);
        //先设置荷载claims
        JwtBuilder builder = Jwts.builder()
                //设置荷载信息
                .setClaims(claims)
                //设置签发日期
                .setIssuedAt(date)
                //设置签发人
                .setSubject(issuer)
                //设置签发算法和密钥
                .signWith(SignatureAlgorithm.HS256,signingKey);
        //设置token的过期时间
        if(ttlMills>0){
            long expMillis = currentTimeMillis + ttlMills;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }
        return builder.compact();
    }
    public static Claims decode(String token){
        return Jwts.parser().setSigningKey(signingKey).parseClaimsJws(token).getBody();
    }
}
